<script lang="ts" setup>
import { isDark } from '@/utils/is'
import { useAppStore } from '@/store/modules/app'
import { useDesign } from '@/hooks/web/useDesign'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import routerSearch from '@/components/RouterSearch/index.vue'
import UserProfileDialog from '@/components/UserProfileDialog/index.vue'
import { useUserStore } from '@/store/modules/user'
import { getAccessToken } from '@/utils/auth'
import * as UserApi from '@/api/system/user'
import { useRouter } from 'vue-router'

defineOptions({ name: 'APP' })

const { getPrefixCls } = useDesign()
const prefixCls = getPrefixCls('app')
const appStore = useAppStore()
const currentSize = computed(() => appStore.getCurrentSize)
const greyMode = computed(() => appStore.getGreyMode)
const { wsCache } = useCache()
const userStore = useUserStore()
const router = useRouter()

// 根据浏览器当前主题设置系统主题色
const setDefaultTheme = () => {
  let isDarkTheme = wsCache.get(CACHE_KEY.IS_DARK)
  if (isDarkTheme === null) {
    isDarkTheme = isDark()
  }
  appStore.setIsDark(isDarkTheme)
}
setDefaultTheme()

// 用户附加信息对话框
const showUserProfileDialog = ref(false)
const hasCheckedProfile = ref(false)

// 检查用户是否填写过附加信息
const checkUserProfile = async () => {
  // 如果没有登录，不检查
  if (!getAccessToken()) {
    return
  }
  
  // 如果已经检查过，不重复检查
  if (hasCheckedProfile.value) {
    return
  }
  
  // 如果用户信息未加载，不检查
  const userId = userStore.user?.id
  if (!userId) {
    return
  }
  
  try {
    hasCheckedProfile.value = true
    console.log('开始检查用户附加信息，userId:', userId)
    const filled = await UserApi.checkFilled(userId)
    console.log('检查结果 filled:', filled)
    // 如果返回 false，表示没有填写过，显示对话框
    if (!filled) {
      console.log('用户未填写过附加信息，显示对话框')
      showUserProfileDialog.value = true
    } else {
      console.log('用户已填写过附加信息，不显示对话框')
    }
  } catch (error) {
    console.error('检查用户附加信息失败:', error)
    hasCheckedProfile.value = false // 检查失败，重置状态以便下次重试
  }
}

// 监听用户信息变化，当用户登录后检查
watch(
  () => userStore.user?.id,
  (userId) => {
    if (userId && !hasCheckedProfile.value) {
      // 延迟检查，确保路由加载完成
      setTimeout(() => {
        checkUserProfile()
      }, 500)
    }
  },
  { immediate: true }
)

// 提交成功后的处理
const handleProfileSuccess = () => {
  hasCheckedProfile.value = true
  showUserProfileDialog.value = false
}
</script>
<template>
  <ConfigGlobal :size="currentSize">
    <RouterView :class="greyMode ? `${prefixCls}-grey-mode` : ''" />
    <routerSearch />
    <!-- 用户附加信息填写对话框 -->
    <UserProfileDialog v-model="showUserProfileDialog" @success="handleProfileSuccess" />
  </ConfigGlobal>
</template>
<style lang="scss">
$prefix-cls: #{$namespace}-app;

.size {
  width: 100%;
  height: 100%;
}

html,
body {
  @extend .size;

  padding: 0 !important;
  margin: 0;
  overflow: hidden;

  #app {
    @extend .size;
  }
}

.#{$prefix-cls}-grey-mode {
  filter: grayscale(100%);
}
</style>
